package com.ikkong.shine.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ikkong.common.config.MainConfig;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.shine.model.DataConnection;
import com.ikkong.shine.model.DbSql;
import com.ikkong.shine.service.DataConnectionService;
import com.ikkong.shine.service.DbSqlService;
import com.ikkong.shine.service.impl.DataConnectionServiceImpl;
import com.ikkong.shine.service.impl.DbSqlServiceImpl;
import com.ikkong.shine.tools.ToolString;
import com.ikkong.system.controller.base.UrlPermissController;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.druid.DruidPlugin;

/**
 * Generated by Blade.
 * 2017-06-30 11:26:43
 */
public class DbSqlController extends UrlPermissController {
	private static String CODE = "dbSql";
	private static String PERFIX = "db_sql";
	private static String LIST_SOURCE = "DbSql.list";
	private static String BASE_PATH = "/platform/dbSql/";
	
	DbSqlService service = new DbSqlServiceImpl();
	DataConnectionService dcs=new DataConnectionServiceImpl(); 
	
	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "dbSql.html");
	}

	public void add() {
		List<Record> list= dcs.querydataname();
		setAttr("list", list);
		setAttr("code", CODE);
		render(BASE_PATH + "dbSql_add.html");
	}

	public void edit() {
		String id = getPara(0);
		DbSql dbSql = service.findById(id);
		setAttr("model", JsonKit.toJson(dbSql));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "dbSql_edit.html");
	}

	public void view() {
		String id = getPara(0);
		DbSql dbSql = service.findById(id);
		setAttr("model", JsonKit.toJson(dbSql));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "dbSql_view.html");
	}

	public void list() {
		Object grid = paginate(LIST_SOURCE);
		renderJson(grid);
	}

	public void save() {
		DbSql dbSql = mapping(PERFIX, DbSql.class);
		dbSql.setLast_time(new Date());
		boolean temp = service.save(dbSql);
		if (temp) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}

	public void update() {
		DbSql dbSql = mapping(PERFIX, DbSql.class);
		//dbSql.setVersion(dbSql.getVersion()+1);
		boolean temp = service.update(dbSql);
		if (temp) {
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}
	
	//获取数据
	public void getSqlConn(){
		Map<String, Object> map=new HashMap<String, Object>();
		//获取选择的数据源id
		String db_source_id=getPara("db_source_id");
		if(ToolString.isBlank(db_source_id)){
			renderJson(error("获取数据源id失败"));
			return;
		}
		//根据选择的数据原id查询连接
		DataConnection dc = dcs.datainfo(db_source_id);
		if(null==dc){
			renderJson(error("查询数据源数据失败"));
			return;
		}
		String driver=dc.getDriver();
		if(ToolString.isBlank(driver)){
			renderJson(error("获取数据库驱动失败"));
		}
		String url=dc.getUrl();
		if(ToolString.isBlank(url)){
			renderJson(error("获取数据库连接失败"));
		}
		String username=dc.getUsername();
		if(ToolString.isBlank(username)){
			renderJson(error("获取数据库用户名失败"));
		}
		String password=dc.getPassword();
		if(ToolString.isBlank(password)){
			renderJson(error("获取数据库密码失败"));
		}
		//
		
		DruidPlugin druidPlugin=null;
		ActiveRecordPlugin arp =null;
		
		
		if(!MainConfig.dbconfigs.contains(dc.getId().toString())){//判断数据源是否已经启动
			
			druidPlugin = new DruidPlugin(url,username,password.trim(),driver);//初始化数据库连接池
			
			arp = new ActiveRecordPlugin(dc.getId().toString(),druidPlugin);//初始化数据源
			druidPlugin.start();//启动连接池
			arp.start();//启动数据源
			MainConfig.dbconfigs.add(dc.getId().toString());//将数据源名称保存在内存常量中
			
		}
		
		String sql = getPara("sqlstring");    //要执行的SQL
        if(ToolString.isBlank(sql)){
        	renderJson(error("请填写需要执行的sql语句"));
        }
        
        List<com.jfinal.plugin.activerecord.Record> recordList=null;
        try {
        	recordList=Db.use(dc.getId().toString()).find(sql);
        }catch (Exception e) {
			//sql执行异常，关闭数据库连接池和数据源
			if(druidPlugin !=null){
				druidPlugin.stop();
			}
			
			if(null != arp){
				arp.stop();
			}
			MainConfig.dbconfigs.remove(dc.getId().toString());//移除添加的数据源名称
			
			//返回sql执行异常信息
			map.put("code", "1");
			map.put("error", e.getMessage());
			System.out.println(e.getMessage());
			renderJson(map);
			return;
			
		}
		
		if(null==recordList){
			map.put("code", "1");
			map.put("error", "查询失败");
			renderJson(map);
			return;
		}else{
			map.put("code", "0");
			map.put("success", "查询成功");
			System.out.println(recordList.size());
			map.put("list", recordList);
			renderJson(map);
		}
		renderJson(map);
	}
	/*
	//获取医生信息
	//获取队列信息
	//获取已分患者信息
	//获取医生与队列信息
	//获取检查项信息
	public void getDataSource(){
		Record record=dcs.dataConnection();
		String driver=record.getStr("driver");
		String url=record.getStr("url");
		String username=record.getStr("username");
		String password=record.getStr("password");
		String id=record.getStr("id");
		DruidPlugin druidPlugin=null;
		ActiveRecordPlugin arp =null;
		if(!MainConfig.dbconfigs.contains(id)){
			druidPlugin = new DruidPlugin(url,username,password.trim(),driver);
			arp = new ActiveRecordPlugin(id,druidPlugin);
			druidPlugin.start();
			arp.start();
			MainConfig.dbconfigs.add(id);
			
			List<Record> list= service.findDbSql();
			String sql="";
			for(int i=0;i<list.size();i++){
				list.get(i).getStr("type");
			}
			for(Record rd:list){
				sql=rd.getStr("sqlstring");
			}
	        List<com.jfinal.plugin.activerecord.Record> recordList=null;
	        try {
	        	recordList=Db.use(id).find(sql);
	        	
	        }catch (Exception e) {
				
				if(druidPlugin !=null){
					druidPlugin.stop();
				}
				
				if(null != arp){
					arp.stop();
				}
				MainConfig.dbconfigs.remove(id);
				renderJson(error("sql错误"));
				return;
			}
			if(null==recordList){
				renderJson("数据同步失败");
				return;
			}else{
				renderJson(success("数据同步成功"));
			}
		}
	}*/
}	